package com.op.service.impl;

import com.auth0.jwt.JWT;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.exceptions.JWTVerificationException;
import com.auth0.jwt.interfaces.DecodedJWT;
import com.op.constants.JWTConstant;
import com.op.entity.User;
import com.op.service.JWTService;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.PropertySource;
import org.springframework.stereotype.Component;

/**
 * ClassName： JWTServiceImpl
 * Date： 2021/10/13 16:03
 *
 * @author 孤焰
 * @version 1.0
 **/

@Component
@PropertySource(value = "classpath:jwt-config.yml")
@ConfigurationProperties(prefix = "jwt")
public class JWTServiceImpl implements JWTService {
    // TODO 只使用@ConfigurationProperties注解无法读取到sign变量，
    //  将yml改成properties可以读取，使用@Value配合此注解也可以读取，只使用@Value会报错（加@Data注解也不行）
    /**
     * jwt加密的签名，初始值见jwt-config.yml文件
     */
    @Value("${sign}")
    private String sign;

    /**
     * jwt加密
     * @param user 实体数据
     * @return token字符串
     */
    @Override
    public String create(User user) {
        return JWT.create()
                .withClaim(JWTConstant.JWT_ID, user.getId())
                .withClaim(JWTConstant.JWT_USERNAME, user.getUsername())
                .withClaim(JWTConstant.JWT_ROLE_ID, user.getRoleId())
                .withClaim(JWTConstant.JWT_AVATAR_PATH, user.getAvatarPath())
                .sign(Algorithm.HMAC256(this.sign));
    }

    /**
     * jwt解密
     * @param token 加密字符串
     * @return 实体数据
     */
    @Override
    public User deCode(String token) throws Exception {
        if (token == null) {
            return null;
        }

        try {
            DecodedJWT decodedJWT = JWT.require(Algorithm.HMAC256(this.sign))
                    .build()
                    .verify(token);
            User user = new User();
            user.setId(decodedJWT.getClaim(JWTConstant.JWT_ID).asLong());
            user.setUsername(decodedJWT.getClaim(JWTConstant.JWT_USERNAME).asString());
            user.setRoleId(decodedJWT.getClaim(JWTConstant.JWT_ROLE_ID).asLong());
            user.setAvatarPath(decodedJWT.getClaim(JWTConstant.JWT_AVATAR_PATH).asString());
            return user;
        } catch (JWTVerificationException e) {
            throw new Exception("请求不合法");
        }
    }
}
